import React, { useEffect, useState } from "react";
import { Modal, Input, message, Popover } from "antd";
import { useNavigate } from "react-router-dom";
import StudentDetail from "./studentDetail";
import { getToken, removeToken } from "@/utils/auth";
import { Tabs } from "antd";
import Loading from "@/conpoments/loading";
import { getChildren, updateChildrenInfo } from "@/api/children";
import "./index.less";

type TTab = {
  key: string;
  label: string;
  children?: React.ReactNode;
  closeIcon?: boolean;
};

const Home = () => {
  const navigate = useNavigate();

  const [adv] = useState(
    `/images/adv/adv-00${Math.ceil(Math.random() * 14)}.webp`
  );
  const [activeKey, setActiveKey] = useState("home");
  const [childList, setChildList] = useState<any[]>([]);
  const [tabs, setTabs] = useState<TTab[]>([
    {
      key: "home",
      label: "首页",
      closeIcon: false,
    },
  ]);
  const [loading, setLoading] = useState(true);

  const openDetail = (data: any) => {
    if (!tabs.some((tab) => tab.key === data.studentId)) {
      setTabs([
        ...tabs,
        {
          key: data.studentId,
          children: <StudentDetail {...data} />,
          label: data.studentName,
        },
      ]);
    }
    setActiveKey(data.studentId);
  };

  const onEdit = (key: any) => {
    const newTabs = tabs.filter((tab) => {
      return tab.key !== key;
    });
    setTabs(newTabs);
    if (activeKey === key) {
      const targetIndex = tabs.findIndex((tab) => tab.key === key);
      setActiveKey(newTabs[targetIndex - 1].key);
    }
  };

  const childListEl = () => {
    return (
      <div style={{ display: activeKey === "home" ? "block" : "none" }}>
        <div className="title-my-children">我的孩子</div>
        {loading ? (
          <div className="loading-container">
            <Loading />
          </div>
        ) : (
          <>
            {childList.length ? (
              <div className="child-container">
                <div className="top-padding"></div>
                <div className="child-list">
                  {childList.map((item, index) => {
                    return (
                      <div
                        className="child-item"
                        key={index}
                        onClick={() => openDetail(item)}
                      >
                        <div>{item.studentName}</div>
                        <div className="child-opts">
                          <div
                            className="look-detail"
                            onClick={(e) => {
                              e.stopPropagation();
                              openChildEdit(item.studentId);
                            }}
                          >
                            编辑
                          </div>
                          <div className="look-detail">查看</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div className="bottom-padding"></div>
              </div>
            ) : (
              <div className="no-data">
                <div>暂无数据...</div>
              </div>
            )}
          </>
        )}
      </div>
    );
  };

  const [modalOpen, setModalOpen] = useState(false);
  const [studentId, setStudentId] = useState("");
  const [height, setHeight] = useState("");
  const [weight, setWeight] = useState("");

  const openChildEdit = (studentId: string) => {
    setHeight("");
    setWeight("");
    setStudentId(studentId);
    setModalOpen(true);
  };
  const handleOk = async () => {
    if (!height || !weight) return message.warning("请输入身高和体重");

    if (!/^\d+(\.\d+)?$/.test(height) || !/^\d+(\.\d+)?$/.test(weight))
      return message.warning("请输正确入身高和体重");

    try {
      const res: any = await updateChildrenInfo({
        studentId,
        weight: parseFloat(weight),
        height: parseFloat(height),
      });
      if (res.statusCode !== 200) return;
      message.success("修改成功");
      setModalOpen(false);
    } catch (error) {
      message.error("修改失败！");
    }
  };
  const handleCancel = () => {
    setModalOpen(false);
  };

  const getChildList = async () => {
    try {
      const res: any = await getChildren();
      if (res?.statusCode === 200) {
        setChildList(res?.data || []);
      }
    } catch (error) {}
    setLoading(false);
  };

  const logout = () => {
    message.success("账号已退出");
    localStorage.removeItem("user-info");
    removeToken();
    navigate("/login");
  };

  const isLogin = getToken() && window.getState("userInfo")?.userId;

  useEffect(() => {
    if (!isLogin) {
      navigate("/login");
      return () => {};
    }

    getChildList();
  }, []);

  return (
    <div className="home-page">
      <div className="home-header">
        <div className="header-title">家长帮</div>
        <div className="header-opts">
          <Popover
            content={
              <div className="logout" onClick={logout}>
                退出登录
              </div>
            }
          >
            <div className="avatar"></div>
          </Popover>
        </div>
      </div>
      <div className="home-main">
        <Tabs
          hideAdd
          onChange={(activeKey) => setActiveKey(activeKey)}
          activeKey={activeKey}
          type="editable-card"
          onEdit={onEdit}
          items={tabs}
        />
        {childListEl()}
      </div>
      <div className="adv">
        <div className="ratio-box">
          <div className="img-box">
            <img className="adv-img" src={adv} alt="" />
            <div className="adv-icon">
              <img src="/images/adv/eva.png" alt="" />
            </div>
          </div>
        </div>
      </div>
      <Modal
        title="修改孩子信息"
        open={modalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText="取消"
        okText="确认"
      >
        <div className="child-info-edit-form">
          <div className="child-info-edit-form-item">
            <div className="child-info-edit-form-item-label">
              {"身高(cm)："}
            </div>
            <Input
              placeholder="请输入孩子的身高"
              value={height}
              onChange={(e) => setHeight(e.target.value)}
            ></Input>
          </div>
          <div className="child-info-edit-form-item">
            <div className="child-info-edit-form-item-label">
              {"体重(kg)："}
            </div>
            <Input
              placeholder="请输入孩子的体重"
              value={weight}
              onChange={(e) => setWeight(e.target.value)}
            ></Input>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default Home;
